from server import db, api_auth, user_opt
from flask import jsonify, Blueprint, request, g
from server.model.sys.sys_log import SysLog
from server.model import set_field, query_by_field
import math

r_sys_log = Blueprint('sys_log', __name__)


@r_sys_log.route('', methods=['GET'])
@api_auth.login_required
def get_sys_logs():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in sys_log_list],
                            }
                """
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=20)
    key_word = request.args.get('key_word')
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    query_filter = request.args.get('filter')

    try:

        sys_log_list = SysLog.query

        sys_log_list = query_by_field(sys_log_list, query_filter, SysLog)

        if start_time:
            sys_log_list = sys_log_list.filter(db.cast(SysLog.create_time, db.Date) >= start_time)

        if end_time:
            sys_log_list = sys_log_list.filter(db.cast(SysLog.create_time, db.Date) <= end_time)
        total = sys_log_list.count()

        sys_log_list = sys_log_list.offset((page - 1) * limit).limit(limit).all()

        user_opt.send({
            "operation": "查询系统日志列表",
            "method": "系统日志管理",
            "params": query_filter,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': [u.to_dict() for u in sys_log_list],
            'totalCount': total,
            'TotalPageCount': math.ceil(int(total / limit))
        })
    except Exception as e:
        print("get sys_logs error:", e)

    return jsonify({'code': 50001, 'message': "查询系统日志时发生错误"})


@r_sys_log.route('', methods=['POST'])
@api_auth.login_required
def add_sys_log():
    """
    @@@
    #### Args:
            {
                user_id: BIGINT(20)    #用户id 
                username: String(64)    #用户名 
                operation: String(64)    #用户操作 
                method: String(64)    #请求方法 
                params: String(64)    #请求参数 
                ip: String(64)    #IP地址 
            }
    #### Returns::
            {'code': 20000, 'message': "系统日志添加成功"}
            {'code': 50001, 'message': "添加系统日志时发生错误"}
    """

    args = request.get_json()

    sys_log = SysLog()
    try:
        set_field(sys_log, args)
        db.session.add(sys_log)
        db.session.commit()

        user_opt.send({
            "operation": "添加系统日志",
            "method": "系统日志管理",
            "params": sys_log.id,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "系统日志添加成功"})
    except Exception as e:
        db.session.rollback()
        print("add sys_log error:", e)

    return jsonify({'code': 50001, 'message': "添加系统日志时发生错误"})


@r_sys_log.route('/<int:pid>', methods=['DELETE'])
@api_auth.login_required
def remove_sys_log(pid):
    """
        @@@
        #### Args:
                sys_log/id
        #### Returns::
                {'code': 20000, 'message': "系统日志删除成功"}
                {'code': 50001, 'message': "删除系统日志时发生错误"}
        """
    try:
        SysLog.query.filter_by(id=pid).delete()
        db.session.commit()

        user_opt.send({
            "operation": "删除系统日志",
            "method": "系统日志管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "系统日志删除成功"})
    except Exception as e:
        print("remove sys_log error:", e)
        return jsonify({
            'code': 50001,
            'message': "删除系统日志时发生错误"
        })


@r_sys_log.route('/<int:pid>', methods=['PUT'])
@api_auth.login_required
def edit_sys_log(pid):
    """
    @@@
    #### Args:
           sys_log/id
    #### Returns::
            {'code': 20000, 'message': "系统日志修改成功"}
            {'code': 50001, 'message': "修改系统日志时发生错误"}
    """
    args = request.get_json()
    try:
        sys_log = SysLog.query.filter_by(id=pid).first()
        set_field(sys_log , args)

        db.session.commit()

        user_opt.send({
            "operation": "修改系统日志",
            "method": "系统日志管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "系统日志修改成功"})
    except Exception as e:
        db.session.rollback()
        print("edit sys_log error:", e)

    return jsonify({'code': 50001, 'message': "修改系统日志时发生错误"})


@r_sys_log.route('/<int:pid>', methods=['GET'])
@api_auth.login_required
def get_detail(pid):
    """
                    @@@
                    #### Args:
                           sys_log/id
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in sys_log_list],
                            }
                """
    sys_log = SysLog.query.filter_by(id=pid).first()
    if not sys_log:
        return jsonify({
            'code': 50002,
            'message': '查询系统日志不存在'
        })

    user_opt.send({
        "operation": "查询系统日志详情",
        "method": "系统日志管理",
        "params": pid,
        "user_id": g.user.id,
        "username": g.user.username
    })

    return jsonify({
        'code': 20000,
        'message': 'success',
        'items': sys_log.to_dict(),
    })

# >>>>> auto generate end <<<<<
